<!DOCTYPE html>

<html class="theme-next mist use-motion" lang="zh-Hans">

<head>
  <!-- hexo-inject:begin --><!-- hexo-inject:end --><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport"
                                                                                  content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="theme-color" content="#222">

  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">

  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">

  <meta http-equiv="Cache-Control" content="no-transform">
  <meta http-equiv="Cache-Control" content="no-siteapp">

  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet"
                                                                                  type="text/css">

  <link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet"
                                                                                  type="text/css">

  <link href="/css/main.css?v=6.0.1" rel="stylesheet" type="text/css">

  <link rel="icon" type="image/png" sizes="16x16"
                                                                                  href="/images/favicon.ico?v=6.0.1">

  <script type="text/javascript" id="hexo.configurations">
    var NexT = window.NexT || {};
    var CONFIG = {
      root: '/',
      scheme: 'Mist',
      version: '6.0.1',
      sidebar: {
        "position": "left",
        "display": "post",
        "offset": 12,
        "b2t": true,
        "scrollpercent": true,
        "onmobile": true
      },
      fancybox: true,
      fastclick: false,
      lazyload: true,
      tabs: true,
      motion: {
        "enable": true,
        "async": false,
        "transition": {
          "post_block": "fadeIn",
          "post_header": "slideDownIn",
          "post_body": "slideDownIn",
          "coll_header": "slideLeftIn",
          "sidebar": "slideUpIn"
        }
      },
      algolia: {
        applicationID: '',
        apiKey: '',
        indexName: '',
        hits: {
          "per_page": 10
        },
        labels: {
          "input_placeholder": "Search for Posts",
          "hits_empty": "We didn't find any results for the search: ${query}",
          "hits_stats": "${hits} results found in ${time} ms"
        }
      }
    };

  </script>

  <link rel="stylesheet" href="mermaid.min.css">
  <script src="https://unpkg.com/mermaid@7.1.0/dist/mermaid.min.js"></script>

  <meta name="keywords" content="python,fabric,远程部署,">

  <meta name="description"
                                                                                  content="最近都在狂写脚本，好像变成 半个运维 一样…刚好有需求写些部署工具，于是了解到了fabric这个模块。下面简单带过一下">
  <meta name="keywords" content="python,fabric,远程部署">
  <meta property="og:type" content="article">
  <meta property="og:title" content="python模块fabric踩坑记录">
  <meta property="og:url"
                                                                                  content="https://tankeryang.github.io/posts/python模块fabric踩坑记录/index.html">
  <meta property="og:site_name" content="淦">
  <meta property="og:description"
                                                                                  content="最近都在狂写脚本，好像变成 半个运维 一样…刚好有需求写些部署工具，于是了解到了fabric这个模块。下面简单带过一下">
  <meta property="og:locale" content="zh-Hans">
  <meta property="og:image"
                                                                                  content="https://tankeryang.github.io/posts/python模块fabric踩坑记录/pic0.jpeg">
  <meta property="og:image"
                                                                                  content="http://www.plantuml.com/plantuml/svg/oq_AIaqkKN19B4aCACglgEJAXmWuv-ULf5QK877JCjEHU7b0EZC_ZuiBhbF1faPN5wuFKnYa7oeB5uEQ0W00">
  <meta property="og:updated_time" content="2019-10-09T17:06:09.615Z">
  <meta name="twitter:card" content="summary">
  <meta name="twitter:title" content="python模块fabric踩坑记录">
  <meta name="twitter:description"
                                                                                  content="最近都在狂写脚本，好像变成 半个运维 一样…刚好有需求写些部署工具，于是了解到了fabric这个模块。下面简单带过一下">
  <meta name="twitter:image"
                                                                                  content="https://tankeryang.github.io/posts/python模块fabric踩坑记录/pic0.jpeg">

  <title>python模块fabric踩坑记录 | 淦</title>

  <noscript>
    <style type="text/css">
      .use-motion .motion-element,
      .use-motion .brand,
      .use-motion .menu-item,
      .sidebar-inner,
      .use-motion .post-block,
      .use-motion .pagination,
      .use-motion .comments,
      .use-motion .post-header,
      .use-motion .post-body,
      .use-motion .collection-title {
        opacity: initial;
      }

      .use-motion .logo,
      .use-motion .site-title,
      .use-motion .site-subtitle {
        opacity: initial;
        top: initial;
      }

      .use-motion {
        .logo-line-before i {
          left: initial;
        }

        .logo-line-after i {
          right: initial;
        }
      }

    </style>
  </noscript><!-- hexo-inject:begin --><!-- hexo-inject:end -->

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  <!-- hexo-inject:begin --><!-- hexo-inject:end --><div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope
                                                                                    itemtype="http://schema.org/WPHeader">
      <div class="header-inner">
        <div class="site-brand-wrapper">
          <div class="site-meta ">

            <div class="custom-logo-site-title">
              <a href="/" class="brand" rel="start">
                <span class="logo-line-before"><i></i></span>
                <span class="site-title">淦</span>
                <span class="logo-line-after"><i></i></span>
              </a>
            </div>

            <p class="site-subtitle">n*m*lg(b)</p>

          </div>

          <div class="site-nav-toggle">
            <button>
              <span class="btn-bar"></span>
              <span class="btn-bar"></span>
              <span class="btn-bar"></span>
            </button>
          </div>
        </div>

        <nav class="site-nav">

          <ul id="menu" class="menu">

            <li class="menu-item menu-item-home">
              <a href="/" rel="section">
                <i class="menu-item-icon fa fa-fw fa-home"></i> <br>home</a>
            </li>

            <li class="menu-item menu-item-archives">
              <a href="/archives/" rel="section">
                <i class="menu-item-icon fa fa-fw fa-archive"></i>
                <br>archives<span class="badge">16</span>
              </a>
            </li>

            <li class="menu-item menu-item-ml-note">
              <a href="/MachineLearningNote" rel="section">
                <i class="menu-item-icon fa fa-fw fa-book"></i> <br>ML Note</a>
            </li>

            <li class="menu-item menu-item-about">
              <a href="/about/" rel="section">
                <i class="menu-item-icon fa fa-fw fa-user"></i> <br>about</a>
            </li>

            <li class="menu-item menu-item-search">

              <a href="javascript:;" class="popup-trigger">

                <i class="menu-item-icon fa fa-search fa-fw"></i> <br>search</a>
            </li>

          </ul>

          <div class="site-search">

            <div class="popup search-popup local-search-popup">
              <div class="local-search-header clearfix">
                <span class="search-icon">
                  <i class="fa fa-search"></i>
                </span>
                <span class="popup-btn-close">
                  <i class="fa fa-times-circle"></i>
                </span>
                <div class="local-search-input-wrapper">
                  <input autocomplete="off" placeholder="searching..." spellcheck="false" type="text"
                                                                                                  id="local-search-input">
                </div>
              </div>
              <div id="local-search-result"></div>
            </div>

          </div>

        </nav>
      </div>
    </header>

    <a href="https://github.com/tankeryang" class="github-corner" target="_blank" title="Follow me on GitHub"
                                                                                    aria-label="Follow me on GitHub"><svg
                                                                                      width="80"
                                                                                      height="80"
                                                                                      viewbox="0 0 250 250"
                                                                                      style="fill:#222; color:#fff; position: absolute; top: 0; border: 0; right: 0;"
                                                                                      aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z" />
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
                                                                                        fill="currentColor"
                                                                                        style="transform-origin: 130px 106px;"
                                                                                        class="octo-arm" />
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
                                                                                        fill="currentColor"
                                                                                        class="octo-body" />
        </svg></a>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">

            <div id="posts" class="posts-expand">

              <div class="reading-progress-bar"></div>

              <article class="post post-type-normal" itemscope
                                                                                              itemtype="http://schema.org/Article">

                <div class="post-block">
                  <link itemprop="mainEntityOfPage"
                                                                                                  href="https://tankeryang.github.io/posts/python模块fabric踩坑记录/">

                  <span hidden itemprop="author" itemscope
                                                                                                  itemtype="http://schema.org/Person">
                    <meta itemprop="name" content="tankeryang">
                    <meta itemprop="description" content>
                    <meta itemprop="image" content="/uploads/girl.jpeg">
                  </span>

                  <span hidden itemprop="publisher" itemscope
                                                                                                  itemtype="http://schema.org/Organization">
                    <meta itemprop="name" content="淦">
                  </span>

                  <header class="post-header">

                    <h1 class="post-title" itemprop="name headline">
                      python模块fabric踩坑记录</h1>

                    <div class="post-meta">
                      <span class="post-time">

                        <span class="post-meta-item-icon">
                          <i class="fa fa-calendar-o"></i>
                        </span>

                        <span class="post-meta-item-text">posted on</span>

                        <time title="创建于" itemprop="dateCreated datePublished"
                                                                                                        datetime="2018-06-11T16:50:41+00:00">2018-06-11</time>

                      </span>

                      <span class="post-category">

                        <span class="post-meta-divider">|</span>

                        <span class="post-meta-item-icon">
                          <i class="fa fa-folder-o"></i>
                        </span>

                        <span class="post-meta-item-text">in</span>

                        <span itemprop="about" itemscope
                                                                                                        itemtype="http://schema.org/Thing"><a
                                                                                                          href="/categories/python/"
                                                                                                          itemprop="url"
                                                                                                          rel="index"><span
                                                                                                            itemprop="name">python</span></a></span>

                      </span>

                      <span class="post-comments-count">
                        <span class="post-meta-divider">|</span>
                        <span class="post-meta-item-icon">
                          <i class="fa fa-comment-o"></i>
                        </span>
                        <a href="/posts/python模块fabric踩坑记录/#comments"
                                                                                                        itemprop="discussionUrl">
                          <span class="post-comments-count valine-comment-count" data-xid="/posts/python模块fabric踩坑记录/"
                                                                                                          itemprop="commentCount"></span>
                        </a>
                      </span>

                      <span id="/posts/python模块fabric踩坑记录/" class="leancloud_visitors"
                                                                                                      data-flag-title="python模块fabric踩坑记录">
                        <span class="post-meta-divider">|</span>
                        <span class="post-meta-item-icon">
                          <i class="fa fa-eye"></i>
                        </span>

                        <span class="post-meta-item-text">read times&#58;</span>

                        <span class="leancloud-visitors-count"></span>
                      </span>

                      <div class="post-wordcount">

                        <span class="post-meta-item-icon">
                          <i class="fa fa-file-word-o"></i>
                        </span>

                        <span class="post-meta-item-text">words
                          count&#58;</span>

                        <span title="words count">18k</span>

                        <span class="post-meta-divider">|</span>

                        <span class="post-meta-item-icon">
                          <i class="fa fa-clock-o"></i>
                        </span>

                        <span class="post-meta-item-text">minutes to read
                          &asymp;</span>

                        <span title="minutes to read">0:39</span>

                      </div>

                    </div>
                  </header>

                  <div class="post-body" itemprop="articleBody">

                    <img src="/posts/python模块fabric踩坑记录/pic0.jpeg">
                    <p>最近都在狂写脚本，好像变成 <strong>半个运维</strong>
                      一样…<br>刚好有需求写些部署工具，于是了解到了<a href="http://www.fabfile.org/" target="_blank"
                                                                                                      rel="noopener">fabric</a>这个模块。下面简单带过一下
                    </p>
                    <a id="more"></a>
                    <h1 id="什么是Fabric"><a href="#什么是Fabric" class="headerlink"
                                                                                                      title="什么是Fabric"></a>什么是Fabric
                    </h1>
                    <p><strong>引用fabric主页的介绍</strong></p>
                    <blockquote>
                      <p>Fabric is a high level Python (2.7, 3.4+) library
                        designed to execute shell
                        commands remotely over SSH, yielding useful Python
                        objects in return</p>
                    </blockquote>
                    <p>意思就是Fabric是基于SSH的远程执行命令，并返回可调用的python对象的框架<br>
                      <div class="note info">
                        <p>
                          Fabric<code>2.x</code>的版本与<code>1.x</code>相比，除了支持<code>python3</code>之外，还做了很多改动。网上很多博客都写的是<code>1.x</code>的版本，参考时要注意。<br><strong>这里主要分析<code>2.x</code>的版本</strong>
                        </p>
                      </div>
                    </p>
                    <p>安装什么的就不废话了，下面来用一下<br>参照他的示例:<br>
                      <figure class="highlight python">
                        <table>
                          <tr>
                            <td class="gutter">
                              <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre>
                            </td>
                            <td class="code">
                              <pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">from</span> fabric <span class="keyword">import</span> Connection</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>result = Connection(<span class="string">'web1.example.com'</span>).run(<span class="string">'uname -s'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>msg = <span class="string">"Ran &#123;.command!r&#125; on &#123;.host&#125;, got this stdout:\n&#123;.stdout&#125;"</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>print(msg.format(result))</span><br><span class="line"></span><br><span class="line">Ran <span class="string">"uname -s"</span> on web1.example.com, got this stdout:</span><br><span class="line">Linux</span><br></pre>
                            </td>
                          </tr>
                        </table>
                      </figure>
                    </p>
                    <p>一目了然</p>
                    <p>下面在公司服务器上测试一下<br>
                      <figure class="highlight python">
                        <table>
                          <tr>
                            <td class="gutter">
                              <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre>
                            </td>
                            <td class="code">
                              <pre><span class="line"><span class="comment"># 服务器ip: 10.10.22.13</span></span><br><span class="line"><span class="comment"># 用户: root</span></span><br><span class="line"></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">from</span> fabric <span class="keyword">import</span> Connection</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>result = Connection(<span class="string">'10.10.22.13'</span>, user=<span class="string">'root'</span>).run(<span class="string">'uname -s'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>msg = <span class="string">"Ran &#123;.command!r&#125; on &#123;.host&#125;, got this stdout:\n&#123;.stdout&#125;"</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>print(msg.format(result))</span><br><span class="line"></span><br><span class="line">Traceback (most recent call last):</span><br><span class="line">  File <span class="string">"/Users/yang/workspace/PycharmProjects/FP-project/inventory_allocate/test/fabric_test.py"</span>, line <span class="number">10</span>, <span class="keyword">in</span> &lt;module&gt;</span><br><span class="line">    result = Connection(<span class="string">"10.10.22.13"</span>, user=<span class="string">'root'</span>).run(<span class="string">"uname -s"</span>)</span><br><span class="line">  File <span class="string">"&lt;decorator-gen-3&gt;"</span>, line <span class="number">2</span>, <span class="keyword">in</span> run</span><br><span class="line">  File <span class="string">"/Users/yang/anaconda3/lib/python3.6/site-packages/fabric/connection.py"</span>, line <span class="number">29</span>, <span class="keyword">in</span> opens</span><br><span class="line">    self.open()</span><br><span class="line">  File <span class="string">"/Users/yang/anaconda3/lib/python3.6/site-packages/fabric/connection.py"</span>, line <span class="number">501</span>, <span class="keyword">in</span> open</span><br><span class="line">    self.client.connect(**kwargs)</span><br><span class="line">  File <span class="string">"/Users/yang/anaconda3/lib/python3.6/site-packages/paramiko/client.py"</span>, line <span class="number">424</span>, <span class="keyword">in</span> connect</span><br><span class="line">    passphrase,</span><br><span class="line">  File <span class="string">"/Users/yang/anaconda3/lib/python3.6/site-packages/paramiko/client.py"</span>, line <span class="number">715</span>, <span class="keyword">in</span> _auth</span><br><span class="line">    <span class="keyword">raise</span> SSHException(<span class="string">'No authentication methods available'</span>)</span><br><span class="line">paramiko.ssh_exception.SSHException: No authentication methods available</span><br></pre>
                            </td>
                          </tr>
                        </table>
                      </figure>
                    </p>
                    <p>呵呵，我他妈就知道，代码里一行ssh的参数毛都没见到，这么容易连上就有鬼了（微笑<br>没的说，填坑要紧</p>
                    <hr>
                    <h1 id="源码分析"><a href="#源码分析" class="headerlink"
                                                                                                      title="源码分析"></a>源码分析
                    </h1>
                    <p>分析报错<br>
                      <figure class="highlight python">
                        <table>
                          <tr>
                            <td class="gutter">
                              <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre>
                            </td>
                            <td class="code">
                              <pre><span class="line">Traceback (most recent call last):</span><br><span class="line">  File <span class="string">"/Users/yang/workspace/PycharmProjects/FP-project/inventory_allocate/test/fabric_test.py"</span>, line <span class="number">10</span>, <span class="keyword">in</span> &lt;module&gt;</span><br><span class="line">    result = Connection(<span class="string">"10.10.22.13"</span>, user=<span class="string">'root'</span>).run(<span class="string">"uname -s"</span>)</span><br><span class="line">  File <span class="string">"&lt;decorator-gen-3&gt;"</span>, line <span class="number">2</span>, <span class="keyword">in</span> run</span><br><span class="line">  File <span class="string">"/Users/yang/anaconda3/lib/python3.6/site-packages/fabric/connection.py"</span>, line <span class="number">29</span>, <span class="keyword">in</span> opens</span><br><span class="line">    self.open()</span><br><span class="line">  File <span class="string">"/Users/yang/anaconda3/lib/python3.6/site-packages/fabric/connection.py"</span>, line <span class="number">501</span>, <span class="keyword">in</span> open</span><br><span class="line">    self.client.connect(**kwargs)</span><br><span class="line">  File <span class="string">"/Users/yang/anaconda3/lib/python3.6/site-packages/paramiko/client.py"</span>, line <span class="number">424</span>, <span class="keyword">in</span> connect</span><br><span class="line">    passphrase,</span><br><span class="line">  File <span class="string">"/Users/yang/anaconda3/lib/python3.6/site-packages/paramiko/client.py"</span>, line <span class="number">715</span>, <span class="keyword">in</span> _auth</span><br><span class="line">    <span class="keyword">raise</span> SSHException(<span class="string">'No authentication methods available'</span>)</span><br><span class="line">paramiko.ssh_exception.SSHException: No authentication methods available</span><br></pre>
                            </td>
                          </tr>
                        </table>
                      </figure>
                    </p>
                    <p>我们可以看到调用堆栈上的错误回溯，定位到<code>line
                        501</code>，在实例化<code>Connection</code>对象后调用<code>client.connect(**kwargs)</code>时抽了…
                    </p>
                    <p>
                      直接摸过去，从<code>Connection</code>类出发往他祖宗上刨，下面先给出继承关系和<code>Connection</code>的关键部分，然后逐块拆分说明:
                    </p>
                    <img
                                                                                                    src="http://www.plantuml.com/plantuml/svg/oq_AIaqkKN19B4aCACglgEJAXmWuv-ULf5QK877JCjEHU7b0EZC_ZuiBhbF1faPN5wuFKnYa7oeB5uEQ0W00">
                    <figure class="highlight python">
                      <figcaption><span>connection.py</span></figcaption>
                      <table>
                        <tr>
                          <td class="gutter">
                            <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br></pre>
                          </td>
                          <td class="code">
                            <pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Connection</span><span class="params">(Context)</span>:</span></span><br><span class="line">    host = <span class="literal">None</span></span><br><span class="line">    original_host = <span class="literal">None</span></span><br><span class="line">    user = <span class="literal">None</span></span><br><span class="line">    port = <span class="literal">None</span></span><br><span class="line">    ssh_config = <span class="literal">None</span></span><br><span class="line">    gateway = <span class="literal">None</span></span><br><span class="line">    forward_agent = <span class="literal">None</span></span><br><span class="line">    connect_timeout = <span class="literal">None</span></span><br><span class="line">    connect_kwargs = <span class="literal">None</span></span><br><span class="line">    client = <span class="literal">None</span></span><br><span class="line">    transport = <span class="literal">None</span></span><br><span class="line">    _sftp = <span class="literal">None</span></span><br><span class="line">    _agent_handler = <span class="literal">None</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">        self,</span></span></span><br><span class="line"><span class="function"><span class="params">        host,</span></span></span><br><span class="line"><span class="function"><span class="params">        user=None,</span></span></span><br><span class="line"><span class="function"><span class="params">        port=None,</span></span></span><br><span class="line"><span class="function"><span class="params">        config=None,</span></span></span><br><span class="line"><span class="function"><span class="params">        gateway=None,</span></span></span><br><span class="line"><span class="function"><span class="params">        forward_agent=None,</span></span></span><br><span class="line"><span class="function"><span class="params">        connect_timeout=None,</span></span></span><br><span class="line"><span class="function"><span class="params">        connect_kwargs=None,</span></span></span><br><span class="line"><span class="function"><span class="params">    )</span>:</span></span><br><span class="line">        <span class="comment"># config</span></span><br><span class="line">        super(Connection, self).__init__(config=config)</span><br><span class="line">        <span class="keyword">if</span> config <span class="keyword">is</span> <span class="literal">None</span>:</span><br><span class="line">            config = Config()</span><br><span class="line">        <span class="keyword">elif</span> <span class="keyword">not</span> isinstance(config, Config):</span><br><span class="line">            config = config.clone(into=Config)</span><br><span class="line">        self._set(_config=config)</span><br><span class="line"></span><br><span class="line">        <span class="comment"># host相关</span></span><br><span class="line">        shorthand = self.derive_shorthand(host)</span><br><span class="line">        host = shorthand[<span class="string">"host"</span>]</span><br><span class="line">        err = (</span><br><span class="line">            <span class="string">"You supplied the &#123;&#125; via both shorthand and kwarg! Please pick one."</span>  <span class="comment"># noqa</span></span><br><span class="line">        )</span><br><span class="line">        <span class="keyword">if</span> shorthand[<span class="string">"user"</span>] <span class="keyword">is</span> <span class="keyword">not</span> <span class="literal">None</span>:</span><br><span class="line">            <span class="keyword">if</span> user <span class="keyword">is</span> <span class="keyword">not</span> <span class="literal">None</span>:</span><br><span class="line">                <span class="keyword">raise</span> ValueError(err.format(<span class="string">"user"</span>))</span><br><span class="line">            user = shorthand[<span class="string">"user"</span>]</span><br><span class="line">        <span class="keyword">if</span> shorthand[<span class="string">"port"</span>] <span class="keyword">is</span> <span class="keyword">not</span> <span class="literal">None</span>:</span><br><span class="line">            <span class="keyword">if</span> port <span class="keyword">is</span> <span class="keyword">not</span> <span class="literal">None</span>:</span><br><span class="line">                <span class="keyword">raise</span> ValueError(err.format(<span class="string">"port"</span>))</span><br><span class="line">            port = shorthand[<span class="string">"port"</span>]</span><br><span class="line"></span><br><span class="line">        <span class="comment"># ssh_config</span></span><br><span class="line">        self.ssh_config = self.config.base_ssh_config.lookup(host)</span><br><span class="line"></span><br><span class="line">        <span class="comment"># original_host</span></span><br><span class="line">        self.original_host = host</span><br><span class="line"></span><br><span class="line">        <span class="comment"># host</span></span><br><span class="line">        self.host = host</span><br><span class="line">        <span class="keyword">if</span> <span class="string">"hostname"</span> <span class="keyword">in</span> self.ssh_config:</span><br><span class="line">            self.host = self.ssh_config[<span class="string">"hostname"</span>]</span><br><span class="line"></span><br><span class="line">        <span class="comment"># user</span></span><br><span class="line">        self.user = user <span class="keyword">or</span> self.ssh_config.get(<span class="string">"user"</span>, self.config.user)</span><br><span class="line"></span><br><span class="line">        <span class="comment"># port</span></span><br><span class="line">        self.port = port <span class="keyword">or</span> int(self.ssh_config.get(<span class="string">"port"</span>, self.config.port))</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> gateway <span class="keyword">is</span> <span class="literal">None</span>:</span><br><span class="line">            <span class="keyword">if</span> <span class="string">"proxyjump"</span> <span class="keyword">in</span> self.ssh_config:</span><br><span class="line">                hops = reversed(self.ssh_config[<span class="string">"proxyjump"</span>].split(<span class="string">","</span>))</span><br><span class="line">                prev_gw = <span class="literal">None</span></span><br><span class="line">                <span class="keyword">for</span> hop <span class="keyword">in</span> hops:</span><br><span class="line">                    <span class="keyword">if</span> prev_gw <span class="keyword">is</span> <span class="literal">None</span>:</span><br><span class="line">                        cxn = Connection(hop)</span><br><span class="line">                    <span class="keyword">else</span>:</span><br><span class="line">                        cxn = Connection(hop, gateway=prev_gw)</span><br><span class="line">                    prev_gw = cxn</span><br><span class="line">                gateway = prev_gw</span><br><span class="line">            <span class="keyword">elif</span> <span class="string">"proxycommand"</span> <span class="keyword">in</span> self.ssh_config:</span><br><span class="line">                gateway = self.ssh_config[<span class="string">"proxycommand"</span>]</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                gateway = self.config.gateway</span><br><span class="line">        self.gateway = gateway</span><br><span class="line"></span><br><span class="line">        <span class="comment"># forward_agent</span></span><br><span class="line">        <span class="keyword">if</span> forward_agent <span class="keyword">is</span> <span class="literal">None</span>:</span><br><span class="line">            forward_agent = self.config.forward_agent</span><br><span class="line">            <span class="keyword">if</span> <span class="string">"forwardagent"</span> <span class="keyword">in</span> self.ssh_config:</span><br><span class="line">                map_ = &#123;<span class="string">"yes"</span>: <span class="literal">True</span>, <span class="string">"no"</span>: <span class="literal">False</span>&#125;</span><br><span class="line">                forward_agent = map_[self.ssh_config[<span class="string">"forwardagent"</span>]]</span><br><span class="line">        self.forward_agent = forward_agent</span><br><span class="line"></span><br><span class="line">        <span class="comment"># connect_timeout</span></span><br><span class="line">        <span class="keyword">if</span> connect_timeout <span class="keyword">is</span> <span class="literal">None</span>:</span><br><span class="line">            connect_timeout = self.ssh_config.get(</span><br><span class="line">                <span class="string">"connecttimeout"</span>, self.config.timeouts.connect</span><br><span class="line">            )</span><br><span class="line">        <span class="keyword">if</span> connect_timeout <span class="keyword">is</span> <span class="keyword">not</span> <span class="literal">None</span>:</span><br><span class="line">            connect_timeout = int(connect_timeout)</span><br><span class="line">        self.connect_timeout = connect_timeout</span><br><span class="line"></span><br><span class="line">        <span class="comment"># connect_kwargs</span></span><br><span class="line">        self.connect_kwargs = self.resolve_connect_kwargs(connect_kwargs)</span><br><span class="line"></span><br><span class="line">        <span class="comment"># client</span></span><br><span class="line">        client = SSHClient()</span><br><span class="line">        client.set_missing_host_key_policy(AutoAddPolicy())</span><br><span class="line">        self.client = client</span><br><span class="line"></span><br><span class="line">        <span class="comment"># transport</span></span><br><span class="line">        self.transport = <span class="literal">None</span></span><br></pre>
                          </td>
                        </tr>
                      </table>
                    </figure>
                    <h2 id="重要的成员变量"><a href="#重要的成员变量" class="headerlink"
                                                                                                      title="重要的成员变量"></a>重要的成员变量
                    </h2>
                    <figure class="highlight python">
                      <figcaption><span>class Connection</span></figcaption>
                      <table>
                        <tr>
                          <td class="gutter">
                            <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre>
                          </td>
                          <td class="code">
                            <pre><span class="line">host = <span class="literal">None</span>             <span class="comment"># 主机名或IP地址: www.host.com, 66.66.66.66</span></span><br><span class="line">original_host = <span class="literal">None</span>    <span class="comment"># 同host</span></span><br><span class="line">user = <span class="literal">None</span>             <span class="comment"># 系统用户名: root, someone</span></span><br><span class="line">port = <span class="literal">None</span>             <span class="comment"># 端口号（远程执行某些应用需提供）</span></span><br><span class="line">gateway = <span class="literal">None</span>          <span class="comment"># 网关</span></span><br><span class="line">forward_agent = <span class="literal">None</span>    <span class="comment"># 代理</span></span><br><span class="line">connect_timeout = <span class="literal">None</span>  <span class="comment"># 超时时间</span></span><br><span class="line">connect_kwargs = <span class="literal">None</span>   <span class="comment"># 连接参数（记住这个，非常重要）</span></span><br><span class="line">client = <span class="literal">None</span>           <span class="comment"># 客户端</span></span><br></pre>
                          </td>
                        </tr>
                      </table>
                    </figure>
                    <h2 id="构造函数参数"><a href="#构造函数参数" class="headerlink"
                                                                                                      title="构造函数参数"></a>构造函数参数
                    </h2>
                    <figure class="highlight python">
                      <figcaption><span>Connection.__init__()</span>
                      </figcaption>
                      <table>
                        <tr>
                          <td class="gutter">
                            <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre>
                          </td>
                          <td class="code">
                            <pre><span class="line">host</span><br><span class="line">user=<span class="literal">None</span></span><br><span class="line">port=<span class="literal">None</span></span><br><span class="line">config=<span class="literal">None</span></span><br><span class="line">gateway=<span class="literal">None</span></span><br><span class="line">forward_agent=<span class="literal">None</span></span><br><span class="line">connect_timeout=<span class="literal">None</span></span><br><span class="line">connect_kwargs=<span class="literal">None</span></span><br></pre>
                          </td>
                        </tr>
                      </table>
                    </figure>
                    <p>
                      这些就是我们在实例化<code>Connection</code>对象时可以控制的一些部分，比较重要的有<code>config</code>和<code>connection_kwargs</code>
                    </p>
                    <h2 id="构造函数主体"><a href="#构造函数主体" class="headerlink"
                                                                                                      title="构造函数主体"></a>构造函数主体
                    </h2>
                    <h3 id="config"><a href="#config" class="headerlink"
                                                                                                      title="config"></a>config
                    </h3>
                    <figure class="highlight python">
                      <figcaption><span>Connection.__init__()</span>
                      </figcaption>
                      <table>
                        <tr>
                          <td class="gutter">
                            <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre>
                          </td>
                          <td class="code">
                            <pre><span class="line">super(Connection, self).__init__(config=config)</span><br><span class="line"><span class="keyword">if</span> config <span class="keyword">is</span> <span class="literal">None</span>:</span><br><span class="line">    config = Config()</span><br><span class="line"><span class="keyword">elif</span> <span class="keyword">not</span> isinstance(config, Config):</span><br><span class="line">    config = config.clone(into=Config)</span><br><span class="line">self._set(_config=config)</span><br></pre>
                          </td>
                        </tr>
                      </table>
                    </figure>
                    <p>
                      <code>config</code>成员变量是一个<code>Config</code>对象，它是调用父类<code>Context.__init__()</code>方法来初始化的。<code>Context.__init__()</code>定义如下:<br>
                      <figure class="highlight python">
                        <figcaption><span>class Context</span></figcaption>
                        <table>
                          <tr>
                            <td class="gutter">
                              <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre>
                            </td>
                            <td class="code">
                              <pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Context</span><span class="params">(DataProxy)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, config=None)</span>:</span></span><br><span class="line">        config = config <span class="keyword">if</span> config <span class="keyword">is</span> <span class="keyword">not</span> <span class="literal">None</span> <span class="keyword">else</span> Config()</span><br><span class="line">        self._set(_config=config)</span><br><span class="line"></span><br><span class="line">        command_prefixes = list()</span><br><span class="line">        self._set(command_prefixes=command_prefixes)</span><br><span class="line"></span><br><span class="line">        command_cwds = list()</span><br><span class="line">        self._set(command_cwds=command_cwds)</span><br></pre>
                            </td>
                          </tr>
                        </table>
                      </figure>
                    </p>
                    <p>
                      具体过程是<code>Context.__init__()</code>初始化时调用<code>_set()</code>绑定了<code>Config</code>成员对象<code>_config</code>:<br>
                      <figure class="highlight python">
                        <figcaption><span>class DataProxy</span></figcaption>
                        <table>
                          <tr>
                            <td class="gutter">
                              <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre>
                            </td>
                            <td class="code">
                              <pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">_set</span><span class="params">(self, *args, **kwargs)</span>:</span></span><br><span class="line">    <span class="keyword">if</span> args:</span><br><span class="line">        object.__setattr__(self, *args)</span><br><span class="line">    <span class="keyword">for</span> key, value <span class="keyword">in</span> six.iteritems(kwargs):</span><br><span class="line">        object.__setattr__(self, key, value)</span><br></pre>
                            </td>
                          </tr>
                        </table>
                      </figure>
                    </p>
                    <p>
                      再通过加了<code>@property</code>的<code>config()</code>函数，使得<code>connection</code>对象能直接用<code>self.config</code>来引用<code>_config</code>:<br>
                      <figure class="highlight python">
                        <figcaption><span>class DataProxy</span></figcaption>
                        <table>
                          <tr>
                            <td class="gutter">
                              <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre>
                            </td>
                            <td class="code">
                              <pre><span class="line"><span class="meta">@property</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">config</span><span class="params">(self)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> self._config</span><br><span class="line"></span><br><span class="line"><span class="meta">@config.setter</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">config</span><span class="params">(self, value)</span>:</span></span><br><span class="line">    self._set(_config=value)</span><br></pre>
                            </td>
                          </tr>
                        </table>
                      </figure>
                    </p>
                    <h3 id="host-user-port"><a href="#host-user-port" class="headerlink"
                                                                                                      title="host, user, port"></a>host,
                      user, port</h3>
                    <figure class="highlight python">
                      <figcaption><span>Connection.__init__()</span>
                      </figcaption>
                      <table>
                        <tr>
                          <td class="gutter">
                            <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre>
                          </td>
                          <td class="code">
                            <pre><span class="line">shorthand = self.derive_shorthand(host)</span><br><span class="line">host = shorthand[<span class="string">"host"</span>]</span><br><span class="line">err = (</span><br><span class="line">    <span class="string">"You supplied the &#123;&#125; via both shorthand and kwarg! Please pick one."</span>  <span class="comment"># noqa</span></span><br><span class="line">)</span><br><span class="line"><span class="keyword">if</span> shorthand[<span class="string">"user"</span>] <span class="keyword">is</span> <span class="keyword">not</span> <span class="literal">None</span>:</span><br><span class="line">    <span class="keyword">if</span> user <span class="keyword">is</span> <span class="keyword">not</span> <span class="literal">None</span>:</span><br><span class="line">        <span class="keyword">raise</span> ValueError(err.format(<span class="string">"user"</span>))</span><br><span class="line">    user = shorthand[<span class="string">"user"</span>]</span><br><span class="line"><span class="keyword">if</span> shorthand[<span class="string">"port"</span>] <span class="keyword">is</span> <span class="keyword">not</span> <span class="literal">None</span>:</span><br><span class="line">    <span class="keyword">if</span> port <span class="keyword">is</span> <span class="keyword">not</span> <span class="literal">None</span>:</span><br><span class="line">        <span class="keyword">raise</span> ValueError(err.format(<span class="string">"port"</span>))</span><br><span class="line">    port = shorthand[<span class="string">"port"</span>]</span><br></pre>
                          </td>
                        </tr>
                      </table>
                    </figure>
                    <p>
                      这段是处理<code>host</code>参数的。<code>host</code>可以有下面集中传入形式:<br>
                      <figure class="highlight plain">
                        <table>
                          <tr>
                            <td class="gutter">
                              <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre>
                            </td>
                            <td class="code">
                              <pre><span class="line">user@host:port  # 例如: root@10.10.10.10:6666</span><br><span class="line">user@host       # 例如: root@10.10.10.10</span><br><span class="line">host:port       # 例如: 10.10.10.10:6666</span><br><span class="line">host            # 例如: 10.10.10.10</span><br></pre>
                            </td>
                          </tr>
                        </table>
                      </figure>
                    </p>
                    <p>
                      前三种会调用<code>self.derive_shorthand(host)</code>分别解析出<code>self.host</code>，<code>self.user</code>和<code>self.port</code>，最后一种需单独传入<code>user</code>，<code>port</code>。<br>如果用前三种传入方式的话，记得不要再重复传入<code>user</code>或<code>port</code>了，会抛出异常
                    </p>
                    <p>源码是真他妈长啊，注释就占了一两百行 (微笑</p>
                    <p>
                      ok，初始化的参数我们先到这里，因为它给的示例也就只有个<code>host</code>而已，一会再讲<code>config_kwags</code>和深入下<code>config</code>。我们现在先去报错的地方:<br>
                      <figure class="highlight python">
                        <figcaption><span>class Connection</span></figcaption>
                        <table>
                          <tr>
                            <td class="gutter">
                              <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre>
                            </td>
                            <td class="code">
                              <pre><span class="line">kwargs = dict(</span><br><span class="line">    self.connect_kwargs,</span><br><span class="line">    username=self.user,</span><br><span class="line">    hostname=self.host,</span><br><span class="line">    port=self.port,</span><br><span class="line">)</span><br><span class="line"><span class="keyword">if</span> self.gateway:</span><br><span class="line">    kwargs[<span class="string">"sock"</span>] = self.open_gateway()</span><br><span class="line"><span class="keyword">if</span> self.connect_timeout:</span><br><span class="line">    kwargs[<span class="string">"timeout"</span>] = self.connect_timeout</span><br><span class="line"><span class="comment"># Strip out empty defaults for less noisy debugging</span></span><br><span class="line"><span class="keyword">if</span> <span class="string">"key_filename"</span> <span class="keyword">in</span> kwargs <span class="keyword">and</span> <span class="keyword">not</span> kwargs[<span class="string">"key_filename"</span>]:</span><br><span class="line">    <span class="keyword">del</span> kwargs[<span class="string">"key_filename"</span>]</span><br><span class="line"><span class="comment"># Actually connect!</span></span><br><span class="line">self.client.connect(**kwargs)  <span class="comment"># 就是你了</span></span><br></pre>
                            </td>
                          </tr>
                        </table>
                      </figure>
                    </p>
                    <p>
                      看到最后一行，传参时将字典<code>kwargs</code>传了过去，<code>kwargs</code>里除了<code>usr</code>，<code>host</code>，<code>port</code>之外，还有一个<code>connect_kwargs</code>。我们看看<code>client.connect()</code>的定义:<br>
                      <figure class="highlight python">
                        <table>
                          <tr>
                            <td class="gutter">
                              <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre>
                            </td>
                            <td class="code">
                              <pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">connect</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">        self,</span></span></span><br><span class="line"><span class="function"><span class="params">        hostname,</span></span></span><br><span class="line"><span class="function"><span class="params">        port=SSH_PORT,</span></span></span><br><span class="line"><span class="function"><span class="params">        username=None,</span></span></span><br><span class="line"><span class="function"><span class="params">        password=None,      # 你</span></span></span><br><span class="line"><span class="function"><span class="params">        pkey=None,          # 你</span></span></span><br><span class="line"><span class="function"><span class="params">        key_filename=None,  # 还有你</span></span></span><br><span class="line"><span class="function"><span class="params">        timeout=None,</span></span></span><br><span class="line"><span class="function"><span class="params">        allow_agent=True,</span></span></span><br><span class="line"><span class="function"><span class="params">        look_for_keys=True,</span></span></span><br><span class="line"><span class="function"><span class="params">        compress=False,</span></span></span><br><span class="line"><span class="function"><span class="params">        sock=None,</span></span></span><br><span class="line"><span class="function"><span class="params">        gss_auth=False,</span></span></span><br><span class="line"><span class="function"><span class="params">        gss_kex=False,</span></span></span><br><span class="line"><span class="function"><span class="params">        gss_deleg_creds=True,</span></span></span><br><span class="line"><span class="function"><span class="params">        gss_host=None,</span></span></span><br><span class="line"><span class="function"><span class="params">        banner_timeout=None,</span></span></span><br><span class="line"><span class="function"><span class="params">        auth_timeout=None,</span></span></span><br><span class="line"><span class="function"><span class="params">        gss_trust_dns=True,</span></span></span><br><span class="line"><span class="function"><span class="params">        passphrase=None,</span></span></span><br><span class="line"><span class="function"><span class="params">    )</span></span></span><br></pre>
                            </td>
                          </tr>
                        </table>
                      </figure>
                    </p>
                    <p>看到<code>6, 7, 8</code>行没？that’s it.</p>
                    <p>接下来我们改写一下一开始的示例:</p>
                    <ul>
                      <li>
                        <p>使用<code>password</code>:</p>
                        <figure class="highlight python">
                          <table>
                            <tr>
                              <td class="gutter">
                                <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre>
                              </td>
                              <td class="code">
                                <pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">from</span> fabric <span class="keyword">import</span> Connection</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="comment"># my_password为10.10.22.13的root用户密码</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>conn = Connection(<span class="string">'10.10.22.13'</span>, user=<span class="string">'root'</span>, connect_kwargs=&#123;<span class="string">'password'</span>: <span class="string">'$&#123;my_password&#125;'</span>&#125;)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>conn.run(<span class="string">"uname -s"</span>)</span><br><span class="line"></span><br><span class="line">Linux</span><br></pre>
                              </td>
                            </tr>
                          </table>
                        </figure>
                      </li>
                      <li>
                        <p>使用<code>key_filename</code>:</p>
                        <figure class="highlight python">
                          <table>
                            <tr>
                              <td class="gutter">
                                <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre>
                              </td>
                              <td class="code">
                                <pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">from</span> fabric <span class="keyword">import</span> Connection</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="comment"># 使用key_filename参数前提需将你的ssh公钥（.pub后缀）添加到远程服务器的.ssh/authorized_keys file里</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="comment"># id_rsa为私钥</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>conn = Connection(<span class="string">'10.10.22.13'</span>, user=<span class="string">'root'</span>, connect_kwargs=&#123;<span class="string">'key_filename'</span>: <span class="string">'$&#123;path to local .ssh dir&#125;/$&#123;your id_rsa file&#125;'</span>&#125;)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>conn.run(<span class="string">"uname -s"</span>)</span><br><span class="line"></span><br><span class="line">Linux</span><br></pre>
                              </td>
                            </tr>
                          </table>
                        </figure>
                      </li>
                    </ul>
                    <p>朋友们，让我们举杯庆祝一下吧</p>
                    <h3 id="connect-kwargs"><a href="#connect-kwargs" class="headerlink"
                                                                                                      title="connect_kwargs"></a>connect_kwargs
                    </h3>
                    <p>我们趁此机会窥视一下<code>connect_keargs</code>的相关部分<br>
                      <figure class="highlight python">
                        <figcaption><span>Connection.__init__()</span>
                        </figcaption>
                        <table>
                          <tr>
                            <td class="gutter">
                              <pre><span class="line">1</span><br></pre>
                            </td>
                            <td class="code">
                              <pre><span class="line">self.connect_kwargs = self.resolve_connect_kwargs(connect_kwargs)</span><br></pre>
                            </td>
                          </tr>
                        </table>
                      </figure>
                    </p>
                    <p>
                      我们看到，当<code>connect_kwargs</code>为<code>None</code>时，会通过<code>config</code>成员变量动态增加属性<code>connect_kwargs</code>属性:<br>
                      <figure class="highlight python">
                        <figcaption>
                          <span>Connection.resolve_connect_kwargs()</span>
                        </figcaption>
                        <table>
                          <tr>
                            <td class="gutter">
                              <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre>
                            </td>
                            <td class="code">
                              <pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">resolve_connect_kwargs</span><span class="params">(self, connect_kwargs)</span>:</span></span><br><span class="line">    <span class="keyword">if</span> connect_kwargs <span class="keyword">is</span> <span class="literal">None</span>:</span><br><span class="line">        connect_kwargs = self.config.connect_kwargs  <span class="comment"># 调用__getattr__()动态增加属性</span></span><br><span class="line">    <span class="keyword">elif</span> <span class="string">"key_filename"</span> <span class="keyword">in</span> self.config.connect_kwargs:</span><br><span class="line">        kwarg_val = connect_kwargs.get(<span class="string">"key_filename"</span>, [])</span><br><span class="line">        conf_val = self.config.connect_kwargs[<span class="string">"key_filename"</span>]</span><br><span class="line">        connect_kwargs[<span class="string">"key_filename"</span>] = conf_val + kwarg_val</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> <span class="string">"identityfile"</span> <span class="keyword">in</span> self.ssh_config:</span><br><span class="line">        connect_kwargs.setdefault(<span class="string">"key_filename"</span>, [])</span><br><span class="line">        connect_kwargs[<span class="string">"key_filename"</span>].extend(</span><br><span class="line">            self.ssh_config[<span class="string">"identityfile"</span>]</span><br><span class="line">        )</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> connect_kwargs</span><br></pre>
                            </td>
                          </tr>
                        </table>
                      </figure>
                    </p>
                    <p>
                      在<code>__getattr__</code>方法里又调用了类方法<code>_get()</code>将<code>connect_kwargs</code>传到<code>key</code>:<br>
                      <figure class="highlight python">
                        <figcaption><span>DataProxy.__getattr__()</span>
                        </figcaption>
                        <table>
                          <tr>
                            <td class="gutter">
                              <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre>
                            </td>
                            <td class="code">
                              <pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">__getattr__</span><span class="params">(self, key)</span>:</span></span><br><span class="line">    <span class="keyword">try</span>:</span><br><span class="line">        <span class="keyword">return</span> self._get(key)  <span class="comment"># 调用_get()</span></span><br><span class="line">    <span class="keyword">except</span> KeyError:</span><br><span class="line">        <span class="keyword">if</span> key <span class="keyword">in</span> self._proxies:</span><br><span class="line">            <span class="keyword">return</span> getattr(self._config, key)</span><br><span class="line">        err = <span class="string">"No attribute or config key found for &#123;!r&#125;"</span>.format(key)</span><br><span class="line">        attrs = [x <span class="keyword">for</span> x <span class="keyword">in</span> dir(self.__class__) <span class="keyword">if</span> <span class="keyword">not</span> x.startswith(<span class="string">'_'</span>)]</span><br><span class="line">        err += <span class="string">"\n\nValid keys: &#123;!r&#125;"</span>.format(</span><br><span class="line">            sorted(list(self._config.keys()))</span><br><span class="line">        )</span><br><span class="line">        err += <span class="string">"\n\nValid real attributes: &#123;!r&#125;"</span>.format(attrs)</span><br><span class="line">        <span class="keyword">raise</span> AttributeError(err)</span><br></pre>
                            </td>
                          </tr>
                        </table>
                      </figure>
                    </p>
                    <p>
                      调用<code>_get()</code>后返回一个<code>DataProxy</code>对象<code>value</code>:<br>
                      <figure class="highlight python">
                        <figcaption><span>DataProxy._get()</span></figcaption>
                        <table>
                          <tr>
                            <td class="gutter">
                              <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre>
                            </td>
                            <td class="code">
                              <pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">_get</span><span class="params">(self, key)</span>:</span></span><br><span class="line">    <span class="keyword">if</span> key <span class="keyword">in</span> (</span><br><span class="line">        <span class="string">'__setstate__'</span>,</span><br><span class="line">    ):</span><br><span class="line">        <span class="keyword">raise</span> AttributeError(key)</span><br><span class="line">    value = self._config[key]</span><br><span class="line">    <span class="keyword">if</span> isinstance(value, dict):</span><br><span class="line">        keypath = (key,)</span><br><span class="line">        <span class="keyword">if</span> hasattr(self, <span class="string">'_keypath'</span>):</span><br><span class="line">            keypath = self._keypath + keypath</span><br><span class="line">        root = getattr(self, <span class="string">'_root'</span>, self)</span><br><span class="line">        value = DataProxy.from_data(</span><br><span class="line">            data=value,</span><br><span class="line">            root=root,</span><br><span class="line">            keypath=keypath,</span><br><span class="line">        )</span><br><span class="line">    <span class="keyword">return</span> value</span><br></pre>
                            </td>
                          </tr>
                        </table>
                      </figure>
                    </p>
                    <p>是不是晕了？呵呵没关系，我他妈也是。就让他随风而去吧</p>
                    <h2 id="fab命令"><a href="#fab命令" class="headerlink"
                                                                                                      title="fab命令"></a>fab命令
                    </h2>
                    <p>
                      安装完<code>fabric</code>后会连同<code>fab</code>工具一起装到<code>python/bin</code>下，在终端输入<code>fab
                        -h</code>查看命令参数<br>简单来说，<code>fab</code>干这么件事，<strong>直接执行当前目录下的<code>fabfile.py</code>脚本里的函数</strong>，下面介绍具体如何写<code>fabfile.py</code>
                    </p>
                    <p>首先按照国际惯例，导入包:<br>
                      <figure class="highlight python">
                        <table>
                          <tr>
                            <td class="gutter">
                              <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                            </td>
                            <td class="code">
                              <pre><span class="line"><span class="keyword">from</span> fabric <span class="keyword">import</span> Connection</span><br><span class="line"><span class="keyword">from</span> invoke <span class="keyword">import</span> task</span><br></pre>
                            </td>
                          </tr>
                        </table>
                      </figure>
                    </p>
                    <p>实例化<code>COnnection</code>对象:<br>
                      <figure class="highlight python">
                        <table>
                          <tr>
                            <td class="gutter">
                              <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                            </td>
                            <td class="code">
                              <pre><span class="line"><span class="comment"># $&#123;&#125;里的内容自行填充</span></span><br><span class="line">conn = Connection(<span class="string">"$&#123;remote host&#125;"</span>, user=<span class="string">'$&#123;remote user&#125;'</span>, connect_kwargs=&#123;<span class="string">'password'</span>: <span class="string">"$&#123;remote user's password&#125;"</span>&#125;)</span><br></pre>
                            </td>
                          </tr>
                        </table>
                      </figure>
                    </p>
                    <p>定义一个功能函数:<br>
                      <figure class="highlight python">
                        <table>
                          <tr>
                            <td class="gutter">
                              <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre>
                            </td>
                            <td class="code">
                              <pre><span class="line"><span class="meta">@task</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">execute</span><span class="params">(c)</span>:</span></span><br><span class="line">    conn.run(<span class="string">"uname -s"</span>)</span><br></pre>
                            </td>
                          </tr>
                        </table>
                      </figure>
                    </p>
                    <p>
                      这个<code>@task</code>装饰器是必须加的，保证<code>fab</code>能直接执行，参数<code>c</code>不用管它，但不能定义成与你实例化的<code>conn</code>同名，原因后面会说
                    </p>
                    <p>保存为<code>fabfile.py</code>:<br>
                      <figure class="highlight python">
                        <figcaption><span>fabfile.py</span></figcaption>
                        <table>
                          <tr>
                            <td class="gutter">
                              <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre>
                            </td>
                            <td class="code">
                              <pre><span class="line"><span class="keyword">from</span> fabric <span class="keyword">import</span> Connection</span><br><span class="line"><span class="keyword">from</span> invoke <span class="keyword">import</span> task</span><br><span class="line"></span><br><span class="line">conn = Connection(<span class="string">"$&#123;remote host&#125;"</span>, user=<span class="string">'$&#123;remote user&#125;'</span>, connect_kwargs=&#123;<span class="string">'password'</span>: <span class="string">"$&#123;remote user's password&#125;"</span>&#125;)</span><br><span class="line"></span><br><span class="line"><span class="meta">@task</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">execute</span><span class="params">(c)</span>:</span></span><br><span class="line">    conn.run(<span class="string">"uname -s"</span>)</span><br></pre>
                            </td>
                          </tr>
                        </table>
                      </figure>
                    </p>
                    <p>在终端执行（服务器系统为Linux）:<br>
                      <figure class="highlight shell">
                        <table>
                          <tr>
                            <td class="gutter">
                              <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                            </td>
                            <td class="code">
                              <pre><span class="line"><span class="meta">$</span><span class="bash"> fab execute</span></span><br><span class="line">Linux  # Linux下的输出</span><br></pre>
                            </td>
                          </tr>
                        </table>
                      </figure>
                    </p>
                    <p>
                      说回参数<code>c</code>，<code>c</code>在这里实际上是本地连接，是<code>localhost</code>的一个<code>Connection</code>对象。我们可以试一下:<br>
                      <figure class="highlight python">
                        <figcaption><span>fabfile.py</span></figcaption>
                        <table>
                          <tr>
                            <td class="gutter">
                              <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre>
                            </td>
                            <td class="code">
                              <pre><span class="line"><span class="keyword">from</span> fabric <span class="keyword">import</span> Connection</span><br><span class="line"><span class="keyword">from</span> invoke <span class="keyword">import</span> task</span><br><span class="line"></span><br><span class="line"><span class="meta">@task</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">execute</span><span class="params">(c)</span>:</span></span><br><span class="line">    c.run(<span class="string">"uname -s"</span>)</span><br></pre>
                            </td>
                          </tr>
                        </table>
                      </figure>
                    </p>
                    <p>在终端执行（我的系统为Mac）:<br>
                      <figure class="highlight shell">
                        <table>
                          <tr>
                            <td class="gutter">
                              <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                            </td>
                            <td class="code">
                              <pre><span class="line"><span class="meta">$</span><span class="bash"> fab execute</span></span><br><span class="line">Darwin  # Mac下的输出</span><br></pre>
                            </td>
                          </tr>
                        </table>
                      </figure>
                    </p>
                    <p>一目了然</p>
                    <p>到这里大家应该大致明白<code>fab</code>是干啥的了。这样的玩法就多了，下面举几个例子:<br>
                      <figure class="highlight python">
                        <figcaption><span>fabfile.py</span></figcaption>
                        <table>
                          <tr>
                            <td class="gutter">
                              <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre>
                            </td>
                            <td class="code">
                              <pre><span class="line"><span class="keyword">from</span> fabric <span class="keyword">import</span> Connection</span><br><span class="line"><span class="keyword">from</span> invoke <span class="keyword">import</span> task</span><br><span class="line"></span><br><span class="line">conn = Connection(<span class="string">"$&#123;remote host&#125;"</span>, user=<span class="string">'$&#123;remote user&#125;'</span>, connect_kwargs=&#123;<span class="string">'password'</span>: <span class="string">"$&#123;remote user's password&#125;"</span>&#125;)</span><br><span class="line"></span><br><span class="line"><span class="meta">@task</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">uname_local</span><span class="params">(c)</span>:</span></span><br><span class="line">    c.run(<span class="string">"uname -s"</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 列出某路径下的文件</span></span><br><span class="line"><span class="meta">@task</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">ls_remote</span><span class="params">(c, dir_path)</span>:</span></span><br><span class="line">    <span class="keyword">with</span> conn.cd(dir_path):</span><br><span class="line">        conn.run(<span class="string">"ls -la"</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 还能在函数里实例化Connection对象</span></span><br><span class="line"><span class="meta">@task</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">uname_rmt</span><span class="params">(c, host, user, password)</span>:</span></span><br><span class="line">    con = Connection(host, user=user, connect_kwargs=&#123;<span class="string">'password'</span>: password&#125;)</span><br><span class="line"></span><br><span class="line">    con.run(<span class="string">"uname -s"</span>)</span><br></pre>
                            </td>
                          </tr>
                        </table>
                      </figure>
                    </p>
                    <p>执行:<br>
                      <figure class="highlight shell">
                        <table>
                          <tr>
                            <td class="gutter">
                              <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre>
                            </td>
                            <td class="code">
                              <pre><span class="line"><span class="meta">$</span><span class="bash"> fab uname_local</span></span><br><span class="line">Darwin</span><br><span class="line"></span><br><span class="line"><span class="meta">$</span><span class="bash"> fab ls_remote /home</span></span><br><span class="line">trendy</span><br><span class="line">td_root</span><br><span class="line"></span><br><span class="line"><span class="meta">$</span><span class="bash"> fab uname_rmt 10.10.22.13 root ******* <span class="comment"># 这个密码就不放出来了</span></span></span><br><span class="line">Linux</span><br></pre>
                            </td>
                          </tr>
                        </table>
                      </figure>
                    </p>
                    <p>具体的<code>Connection</code>还封装了哪些命令，就需要大家在使用中探索了</p>
                    <h1 id="fab-1-x-与-fab-2-x"><a href="#fab-1-x-与-fab-2-x" class="headerlink"
                                                                                                      title="fab 1.x 与 fab 2.x"></a>fab
                      1.x 与 fab 2.x</h1>
                    <p><code>fab 1.x</code>与<code>fab 2.x</code>最大的不同就是<code>fab
                        2.x</code>没有了<code>env</code>模块，所有的操作都基于<code>Connection</code>对象完成，对于<code>fab</code>命令的调用，将暴露方法封装到<code>invoke</code>模块，使其独立出来。这是我觉得最大的不同。只是现在还没有很多的博客写到<code>fab
                        2.x</code>的一些特性，官方文档也很简单，还是需要大家花时间阅读下源码才能清楚里面的逻辑</p>
                    <p>有时间的话会再对<code>fabric</code>做个详细剖析</p>

                  </div>

                  <div>

                    <div>

                      <div
                                                                                                      style="text-align:center;color: #ccc;font-size:14px;">
                        ---------------------------------END---------------------------------
                      </div>

                    </div>

                  </div>

                  <div>
                    <div
                                                                                                    style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
                      <div>手抖一下？</div>
                      <button id="rewardButton" disable="enable"
                                                                                                      onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
                        <span>献爱心</span>
                      </button>
                      <div id="QR" style="display: none;">

                        <div id="wechat" style="display: inline-block">
                          <img id="wechat_qr" src="/images/wx_pay1.png"
                                                                                                          alt="tankeryang WechatPay">
                          <p>WechatPay</p>
                        </div>

                      </div>
                    </div>

                  </div>

                  <footer class="post-footer">

                    <div class="post-tags">

                      <a href="/tags/python/" rel="tag"><i
                                                                                                        class="fa fa-tag"></i>
                        python</a>

                      <a href="/tags/fabric/" rel="tag"><i
                                                                                                        class="fa fa-tag"></i>
                        fabric</a>

                      <a href="/tags/远程部署/" rel="tag"><i class="fa fa-tag"></i>
                        远程部署</a>

                    </div>

                    <div class="post-widgets">

                      <div id="needsharebutton-postbottom">
                        <span class="btn">
                          <i class="fa fa-share-alt" aria-hidden="true"></i>
                        </span>
                      </div>

                    </div>

                    <div class="post-nav">
                      <div class="post-nav-next post-nav-item">

                        <a href="/posts/服务器安装anaconda与配置jupyter反向代理/" rel="next"
                                                                                                        title="服务器安装anaconda与配置jupyter反向代理">
                          <i class="fa fa-chevron-left"></i>
                          服务器安装anaconda与配置jupyter反向代理
                        </a>

                      </div>

                      <span class="post-nav-divider"></span>

                      <div class="post-nav-prev post-nav-item">

                        <a href="/posts/半次元爬虫-banciyuan-downloader-v2-0-更新/" rel="prev"
                                                                                                        title="半次元爬虫 banciyuan-downloader v2.0 更新">
                          半次元爬虫 banciyuan-downloader v2.0 更新 <i
                                                                                                          class="fa fa-chevron-right"></i>
                        </a>

                      </div>
                    </div>

                  </footer>
                </div>

              </article>

              <div class="post-spread">

                <!-- Go to www.addthis.com/dashboard to customize your tools -->
                <div class="addthis_inline_share_toolbox">
                  <script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-59b14058bcac3b78"
                                                                                                  async="async">
                  </script>
                </div>

              </div>
            </div>

          </div>

          <div class="comments" id="comments">
          </div>

        </div>

        <div class="sidebar-toggle">
          <div class="sidebar-toggle-line-wrap">
            <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
            <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
            <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
          </div>
        </div>

        <aside id="sidebar" class="sidebar">

          <div id="sidebar-dimmer"></div>

          <div class="sidebar-inner">

            <ul class="sidebar-nav motion-element">
              <li class="sidebar-nav-toc sidebar-nav-active"
                                                                                              data-target="post-toc-wrap">
                文章目录
              </li>
              <li class="sidebar-nav-overview" data-target="site-overview-wrap">
                站点概览
              </li>
            </ul>

            <section class="site-overview-wrap sidebar-panel">
              <div class="site-overview">
                <div class="site-author motion-element" itemprop="author" itemscope
                                                                                                itemtype="http://schema.org/Person">

                  <a href="/" class="site-author-image" rel="start"
                                                                                                  style="border:none">
                    <img class="site-author-image" itemprop="image" src="/uploads/girl.jpeg"
                                                                                                    alt="tankeryang">
                  </a>

                  <p class="site-author-name" itemprop="name">tankeryang</p>
                  <p class="site-description motion-element"
                                                                                                  itemprop="description">
                    汝亦知射乎？吾射不亦精乎？</p>
                </div>

                <nav class="site-state motion-element">

                  <div class="site-state-item site-state-posts">

                    <a href="/archives/">

                      <span class="site-state-item-count">16</span>
                      <span class="site-state-item-name">日志</span>
                    </a>
                  </div>

                  <div class="site-state-item site-state-categories">
                    <a href="/categories/index.html">
                      <span class="site-state-item-count">7</span>
                      <span class="site-state-item-name">分类</span>
                    </a>
                  </div>

                  <div class="site-state-item site-state-tags">
                    <a href="/tags/index.html">
                      <span class="site-state-item-count">28</span>
                      <span class="site-state-item-name">标签</span>
                    </a>
                  </div>

                </nav>

                <div class="links-of-author motion-element">

                  <span class="links-of-author-item">
                    <a href="https://github.com/tankeryang" target="_blank"
                                                                                                    title="GitHub">

                      <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>

                  <span class="links-of-author-item">
                    <a href="mailto:youngzyang@outlook.com" target="_blank"
                                                                                                    title="E-Mail">

                      <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>

                </div>

                <div class="cc-license motion-element" itemprop="license">
                  <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity"
                                                                                                  target="_blank">
                    <img src="/images/cc-by-nc-sa.svg" alt="Creative Commons">
                  </a>
                </div>

                <div
                                                                                                class="links-of-blogroll motion-element links-of-blogroll-block">
                  <div class="links-of-blogroll-title">
                    <i class="fa  fa-fw fa-link"></i>
                    博客镜像 & 友情链接
                  </div>
                  <ul class="links-of-blogroll-list">

                    <li class="links-of-blogroll-item">
                      <a href="https://tankeryang.github.io" title="淦 - github"
                                                                                                      target="_blank">淦
                        - github</a>
                    </li>

                    <li class="links-of-blogroll-item">
                      <a href="https://tankeryang.coding.me" title="淦 - coding"
                                                                                                      target="_blank">淦
                        - coding</a>
                    </li>

                    <li class="links-of-blogroll-item">
                      <a href="http://tankeryang.gitee.io" title="淦 - gitee"
                                                                                                      target="_blank">淦
                        - gitee</a>
                    </li>

                    <li class="links-of-blogroll-item">
                      <a href="https://deeeeeeeee.github.io" title="未知"
                                                                                                      target="_blank">未知</a>
                    </li>

                    <li class="links-of-blogroll-item">
                      <a href="https://www.tiexo.cn/" title="简单可依赖"
                                                                                                      target="_blank">简单可依赖</a>
                    </li>

                    <li class="links-of-blogroll-item">
                      <a href="https://darrenliuwei.com" title="刘伟"
                                                                                                      target="_blank">刘伟</a>
                    </li>

                  </ul>
                </div>

              </div>
            </section>

            <!--noindex-->
            <section
                                                                                            class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
              <div class="post-toc">

                <div class="post-toc-content">
                  <ol class="nav">
                    <li class="nav-item nav-level-1"><a class="nav-link"
                                                                                                      href="#什么是Fabric"><span
                                                                                                        class="nav-number">1.</span>
                        <span class="nav-text">什么是Fabric
                        </span></a></li>
                    <li class="nav-item nav-level-1"><a class="nav-link"
                                                                                                      href="#源码分析"><span
                                                                                                        class="nav-number">2.</span>
                        <span class="nav-text">源码分析</span></a>
                      <ol class="nav-child">
                        <li class="nav-item nav-level-2"><a class="nav-link"
                                                                                                          href="#重要的成员变量"><span
                                                                                                            class="nav-number">2.1.</span>
                            <span class="nav-text">重要的成员变量
                            </span></a></li>
                        <li class="nav-item nav-level-2"><a class="nav-link"
                                                                                                          href="#构造函数参数"><span
                                                                                                            class="nav-number">2.2.</span>
                            <span class="nav-text">构造函数参数
                            </span></a></li>
                        <li class="nav-item nav-level-2"><a class="nav-link"
                                                                                                          href="#构造函数主体"><span
                                                                                                            class="nav-number">2.3.</span>
                            <span class="nav-text">构造函数主体
                            </span></a>
                          <ol class="nav-child">
                            <li class="nav-item nav-level-3"><a class="nav-link"
                                                                                                              href="#config"><span
                                                                                                                class="nav-number">2.3.1.</span>
                                <span class="nav-text">config
                                </span></a></li>
                            <li class="nav-item nav-level-3"><a class="nav-link"
                                                                                                              href="#host-user-port"><span
                                                                                                                class="nav-number">2.3.2.</span>
                                <span class="nav-text">host,
                                  user, port</span></a></li>
                            <li class="nav-item nav-level-3"><a class="nav-link"
                                                                                                              href="#connect-kwargs"><span
                                                                                                                class="nav-number">2.3.3.</span>
                                <span class="nav-text">connect_kwargs
                                </span></a></li>
                          </ol>
                        </li>
                        <li class="nav-item nav-level-2"><a class="nav-link"
                                                                                                          href="#fab命令"><span
                                                                                                            class="nav-number">2.4.</span>
                            <span class="nav-text">fab命令</span></a></li>
                      </ol>
                    </li>
                    <li class="nav-item nav-level-1"><a class="nav-link"
                                                                                                      href="#fab-1-x-与-fab-2-x"><span
                                                                                                        class="nav-number">3.</span>
                        <span class="nav-text">fab
                          1.x 与 fab 2.x</span></a></li>
                  </ol>
                </div>

              </div>
            </section>
            <!--/noindex-->

            <div class="back-to-top">
              <i class="fa fa-arrow-up"></i>

              <span id="scrollpercent"><span>0</span>%</span>

            </div>

          </div>
        </aside>

      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <hr>
        <div class="copyright">&copy; 2017 &mdash; <span
                                                                                          itemprop="copyrightYear">2019</span>
          <span class="with-love">
            <i class="fa fa-cog fa-spin fa-1x fa-fw"></i>
          </span>
          <span class="author" itemprop="copyrightHolder">tankeryang</span>

          <span class="post-meta-divider">|</span>
          <span class="post-meta-item-icon">
            <i class="fa fa-area-chart"></i>
          </span>

          <span title="total count">131k</span>

          <span class="post-meta-divider">|</span>
          <span class="post-meta-item-icon">
            <i class="fa fa-coffee"></i>
          </span>

          <span title="total time">4:51</span>

        </div>

        <div class="powered-by">Powered by — <a class="theme-link" target="_blank"
                                                                                          href="https://hexo.io">Hexo</a>
        </div>

        <span class="post-meta-divider">|</span>

        <div class="theme-info">theme &mdash; <a class="theme-link" target="_blank"
                                                                                          href="https://github.com/theme-next/hexo-theme-next">NexT.Mist</a>
          v6.0.1</div>

        <div class="busuanzi-count">
          <script async
                                                                                          src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js">
          </script>

          <span class="site-uv">
            <i class="fa fa-user"></i>
            <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
            visitors
          </span>

        </div>

      </div>
    </footer>

  </div>

  <script type="text/javascript">
    if (Object.prototype.toString.call(window.Promise) !==
      '[object Function]') {
      window.Promise = null;
    }

  </script>

  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  <script type="text/javascript"
                                                                                  src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7">
  </script>

  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1">
  </script>

  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1">
  </script>

  <script type="text/javascript"
                                                                                  src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5">
  </script>

  <script type="text/javascript"
                                                                                  src="/lib/reading_progress/reading_progress.js">
  </script>

  <script type="text/javascript" src="/js/src/utils.js?v=6.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.0.1"></script>

  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.0.1"></script>
  <script type="text/javascript" src="/js/src/post-details.js?v=6.0.1"></script>

  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.0.1"></script>

  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>

  <script type="text/javascript">
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.indexOf(item) > -1;
    });
    new Valine({
      el: '#comments',
      verify: true,
      notify: false,
      appId: 'NiFbgAF3vRyR2BayGJOswb21-gzGzoHsz',
      appKey: 'xGF7qavyOOQGtVACk06SnLrW',
      placeholder: '填上邮箱可以收到回复的邮件提醒哦～',
      avatar: 'retro',
      guest_info: guest,
      pageSize: '10' || 10,
    });

  </script>

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;
    var onPopupClose = function(e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append(
          '<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';
      // start loading animation
      $("body")
        .append(
          '<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css(
        'text-align', 'center');
      // ref: https://github.com/ForbesLindesay/unescape-html
      var unescapeHtml = function(html) {
        return String(html)
          .replace(/&quot;/g, '"')
          .replace(/&#39;/g, '\'')
          .replace(/&#x3A;/g, ':')
          // replace all the other &#x; chars
          .replace(/&#(\d+);/g, function(m, p) {
            return String.fromCharCode(p);
          })
          .replace(/&lt;/g, '<')
          .replace(/&gt;/g, '>')
          .replace(/&amp;/g, '&');
      };
      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content", this).text(),
              url: $("url", this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(
                  /<[^>]+>/g, "");
                content = unescapeHtml(content);
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if (title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text,
                      caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0,
                        position = [],
                        index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word,
                          startPosition)) > -1) {
                        index.push({
                          position: position,
                          word: word
                        });
                        startPosition = position + wordLen;
                      }
                      return index;
                    }
                    indexOfTitle = indexOfTitle.concat(
                      getIndexByWord(keyword,
                        titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(
                      getIndexByWord(keyword,
                        contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent
                    .length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length +
                      indexOfContent.length;
                  }
                }
                // show search results
                if (isMatch) {
                  // sort index by position of keyword
                  [indexOfTitle, indexOfContent].forEach(function(
                    index) {
                    index.sort(function(itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft
                        .position) {
                        return itemRight.position -
                          itemLeft.position;
                      } else {
                        return itemLeft.word.length -
                          itemRight.word.length;
                      }
                    });
                  });
                  // merge hits into slices
                  function mergeIntoSlice(text, start, end,
                  index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index
                      .length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({
                        position: position,
                        length: word.length
                      });
                      var wordEnd = position + word.length;
                      // move to next position of hit
                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }
                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0,
                      title.length, indexOfTitle));
                  }
                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent
                      .length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if (start < 0) {
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if (end > content.length) {
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content,
                      start, end, indexOfContent));
                  }
                  // sort slices in content by search text's count and hits' count
                  slicesOfContent.sort(function(sliceLeft,
                    sliceRight) {
                    if (sliceLeft.searchTextCount !==
                      sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount -
                        sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !==
                      sliceRight.hits.length) {
                      return sliceRight.hits.length -
                        sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight
                        .start;
                    }
                  });
                  // select top N slices in content
                  var upperBound = parseInt('-1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0,
                      upperBound);
                  }
                  // highlight title and content
                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function(hit) {
                      result += text.substring(prevEnd, hit
                        .position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' +
                        text.substring(hit.position, end) +
                        '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }
                  var resultItem = '';
                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl +
                      "' class='search-result-title'>" +
                      highlightKeyword(title, slicesOfTitle[0]) +
                      "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl +
                      "' class='search-result-title'>" + title +
                      "</a>";
                  }
                  slicesOfContent.forEach(function(slice) {
                    resultItem += "<a href='" + articleUrl +
                      "'>" +
                      "<p class=\"search-result\">" +
                      highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });
                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML =
                '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML =
                '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function(resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight
                  .searchTextCount) {
                  return resultRight.searchTextCount - resultLeft
                    .searchTextCount;
                } else if (resultLeft.hitCount !== resultRight
                  .hitCount) {
                  return resultRight.hitCount - resultLeft
                    .hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList =
                '<ul class=\"search-result-list\">';
              resultItems.forEach(function(result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }
          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function(event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }
          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');
          proceedsearch();
        }
      });
    }
    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });
    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e) {
      e.stopPropagation();
    });
    $(document).on('keyup', function(event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });

  </script>

  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>
    AV.initialize("NiFbgAF3vRyR2BayGJOswb21-gzGzoHsz",
      "xGF7qavyOOQGtVACk06SnLrW");

  </script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");
      $visitors.each(function() {
        entries.push($(this).attr("id").trim());
      });
      query.containedIn('url', entries);
      query.find()
        .done(function(results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';
          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }
          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);
            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for (var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if (countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function(object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);
      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(
                  counter.get('time'));
              },
              error: function(counter, error) {
                console.log(
                  'Failed to save Visitor num, with error message: ' +
                  error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(
                  newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }
    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });

  </script>

  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    pbOptions = {};
    pbOptions.iconStyle = "box";
    pbOptions.boxForm = "horizontal";
    pbOptions.position = "topCenter";
    pbOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
    new needShareButton('#needsharebutton-postbottom', pbOptions);

  </script>

  <script src="/lib/pangu/dist/pangu.min.js?v=3.3"></script>
  <script type="text/javascript">
    pangu.spacingPage();

  </script>

  <script type="text/javascript" src="/js/src/exturl.js?v=6.0.1"></script><!-- hexo-inject:begin --><!-- Begin: Injected MathJax -->
<script type="text/x-mathjax-config">
  MathJax.Hub.Config("");
</script>

<script type="text/x-mathjax-config">
  MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for(i=0; i < all.length; i += 1) {
      all[i].SourceElement().parentNode.className += ' has-jax';
    }
  });
</script>

<script type="text/javascript" src="custom_mathjax_source">
</script>
<!-- End: Injected MathJax -->
<!-- hexo-inject:end -->

</body>

</html>
